import react, { useEffect, useLayoutEffect, useRef } from "react";
import "./index.less";
import pic1 from "../../assets/pic1.jpeg";
interface HuaBuProps {
  imgUrl: string;

  scale?: number;
  points: Array<{
    x: number;
    y: number;
    ex: number;
    ey: number;
  }>;
  allowManualSelection?: boolean;
}

const setStrokeStyle = (ctx: CanvasRenderingContext2D) => {
  // 设置边框样式：深蓝色
  ctx.strokeStyle = "#1a237e"; // 深蓝色（偏暗）
  ctx.lineWidth = 2;

  // 设置填充样式：浅蓝色半透明
  ctx.fillStyle = "rgba(173, 216, 230, 0.5)"; // 浅蓝色 + 50% 透明度
};
// 定义点的类型
type Point = { x: number; y: number };

class Shape {
  constructor(
    public x: number, // x 坐标
    public y: number, // y 坐标
    public ctx: CanvasRenderingContext2D, // 画布上下文
    public ex: number = x, // 终点 x 坐标（默认值）
    public ey: number = y, // 终点 y 坐标（默认值）
    public points: Point[] = [] // 路径点数组
  ) {}

  draw(): void {
    this.drawRect();
  }

  drawLine(): void {
    this.ctx.beginPath();
    this.ctx.save();
    setStrokeStyle(this.ctx);
    this.ctx.moveTo(this.x, this.y);
    this.points.forEach(({ x, y }) => this.ctx.lineTo(x, y));
    this.ctx.stroke();
    this.ctx.restore();
  }

  drawRect(): void {
    this.ctx.save();
    setStrokeStyle(this.ctx); // 使用修复后的函数名

    const x = Math.min(this.x, this.ex);
    const y = Math.min(this.y, this.ey);
    const width = Math.abs(this.x - this.ex);
    const height = Math.abs(this.y - this.ey);

    this.ctx.fillRect(x, y, width, height); // 填充
    this.ctx.strokeRect(x, y, width, height); // 描边

    this.ctx.restore();
  }

  // 其他方法（保持简洁）
  drawCircle(): void {}
  drawFill(): void {}
  drawRubber(): void {}
}

export default function HuaBu(props: HuaBuProps) {
  const { imgUrl, scale = 1, points, allowManualSelection = false } = props;

  const canvas1Ref = useRef<HTMLCanvasElement>(null);
  const canvas2Ref = useRef<HTMLCanvasElement>(null);
  let ctx1: CanvasRenderingContext2D;
  let ctx2: CanvasRenderingContext2D;

  useLayoutEffect(() => {
    if (canvas1Ref.current && canvas2Ref.current) {
      ctx1 = canvas1Ref.current.getContext("2d") as CanvasRenderingContext2D;
      ctx2 = canvas2Ref.current.getContext("2d") as CanvasRenderingContext2D;

      const image = new Image();
      image.src = pic1;
      image.onload = () => {
        if (canvas1Ref.current && canvas2Ref.current) {
          //   const clientWidth =
          //     window.innerWidth ||
          //     document.documentElement.clientWidth ||
          //     document.body.clientWidth;
          //   const clientHeight =
          //     window.innerHeight ||
          //     document.documentElement.clientHeight ||
          //     document.body.clientHeight;

          if (scale) {
            image.width = image.width * scale;
            image.height = image.height * scale;
          }

          canvas1Ref.current.width = image.width;
          canvas1Ref.current.height = image.height;
          ctx1.drawImage(image, 0, 0, image.width, image.height);
          canvas2Ref.current.width = image.width;
          canvas2Ref.current.height = image.height;

          if (Array.isArray(points) && points.length) {
            points.forEach((pointItem) => {
              const { x, y, ex, ey } = pointItem;
              let shape = new Shape(
                x * scale,
                y * scale,
                ctx2,
                ex * scale,
                ey * scale
              );
              requestAnimationFrame(shape.draw.bind(shape));
            });
          }
        }
      };
    }
  }, []);

  const setStrokeStype = (ctx: CanvasRenderingContext2D) => {
    // 设置边框样式：深蓝色
    ctx.strokeStyle = "#1a237e"; // 深蓝色（偏暗）
    ctx.lineWidth = 2;

    // 设置填充样式：浅蓝色半透明
    ctx.fillStyle = "rgba(173, 216, 230, 0.5)"; // 浅蓝色 + 50% 透明度
  };

  const handleMoouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const area = canvas2Ref.current!.getBoundingClientRect();
    let x = e.clientX - area.left;
    let y = e.clientY - area.top;
    console.log("mousedown坐标", { x, y });
    let shape = new Shape(x, y, ctx2);
    ctx2.beginPath();
    // 其他图形都需要拖拽来绘制
    ctx2.save();
    setStrokeStype(ctx2);
    ctx2.moveTo(x, y);
    window.onmousemove = function (e) {
      let ex = e.clientX - area.left;
      let ey = e.clientY - area.top;
      ctx2.clearRect(
        0,
        0,
        canvas2Ref.current!.width,
        canvas2Ref.current!.height
      );
      shape.ex = ex;
      shape.ey = ey;
      shape.draw();
    };

    window.onmouseup = function () {
      window.onmousemove = null;
      window.onmouseup = null;
      ctx2.restore();
      shape.ctx = ctx1;
      shape.draw();
      console.log(shape, "shape");
      ctx2.clearRect(
        0,
        0,
        canvas2Ref.current!.width,
        canvas2Ref.current!.height
      );
    };
  };
  return (
    <div>
      <canvas id="canvas1" ref={canvas1Ref}></canvas>
      <canvas
        id="canvas2"
        ref={canvas2Ref}
        onMouseDown={allowManualSelection ? handleMoouseDown : undefined}
      ></canvas>
    </div>
  );
}
